package com.yl.springbootrabbitmq.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.ReturnedMessage;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

/**
 * @author yangl
 * @Description: 回调
 */
@Slf4j
@Component
public class MyCallBack implements RabbitTemplate.ConfirmCallback ,RabbitTemplate.ReturnsCallback{

    @Resource
    private RabbitTemplate rabbitTemplate;

    @PostConstruct
    public void init(){
        //注入
        rabbitTemplate.setConfirmCallback(this::confirm);
        rabbitTemplate.setReturnsCallback(this::returnedMessage);
    }

    /**
     * 交换机确认回调方法
     * 1、发送消息，交换机接收到了，回调
     *  1.1、correlationData 保存回调信息的ID和相关信息
     *  1.2、交换机收到消息 ack = true
     *  1.3、cause 成功了，没有原因，为null
     * 2、发送消息，交换机接收失败了，回调
     *  2.1、correlationData 保存回调信息的ID和相关信息
     *  2.2、交换机收到消息 ack = false
     *  2.3、cause 发送失败的原因
     */
    @Override
    public void confirm(CorrelationData correlationData, boolean ack, String cause) {
        String id = correlationData != null ? correlationData.getId() : "";
        if(ack){
            log.info("交换机已经接收到ID为：{}的消息", id);
        } else {
            log.info("交换机没有接收到ID为：{}的消息，原因是：",id, cause);
        }
    }

    @Override
    public void returnedMessage(ReturnedMessage returned) {
        log.error("消息{}，被交换机{}退回，退回原因：{}，路由Key：{}",
                new String(returned.getMessage().getBody()),returned.getExchange(),
                returned.getReplyText(), returned.getRoutingKey());

    }
}
